package io.github.aaron.commonadmin.manager;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @Author aaron01.fan
 * @Date 2025/9/1 18:18
 * @Description freemarker管理器,基于单例实现
 **/
public class FreemarkerTemplateManager {

    private final Configuration cfg;

    {
        cfg = new Configuration(Configuration.VERSION_2_3_34);
        cfg.setClassForTemplateLoading(FreemarkerTemplateManager.class, "/ftl"); // 模板所在目录
        cfg.setDefaultEncoding(StandardCharsets.UTF_8.name());
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        cfg.setLogTemplateExceptions(false);
        cfg.setWrapUncheckedExceptions(true);
    }

    private FreemarkerTemplateManager(){}

    public static FreemarkerTemplateManager getInstance(){
        return Holder.instance;
    }

    public String process(String templateRelatePath, Map<String,Object> params) {
        try{
            Template template = cfg.getTemplate(templateRelatePath);
            StringWriter sw = new StringWriter();
            template.process(params, sw);
            return sw.toString();
        }catch (Exception e){
            throw new RuntimeException("FreemarkerTemplateManager process填充模板异常",e);
        }
    }

    private static class Holder{

        public static final FreemarkerTemplateManager instance = new FreemarkerTemplateManager();

    }

}
